package com.mark.controller.common.interceptor;

import com.google.common.collect.Maps;
import com.mark.common.ServerResponse;
import com.mark.pojo.Admin;
import com.mark.util.CookieUtil;
import com.mark.util.JsonUtil;
import com.mark.util.PropertiesUtil;
import com.mark.util.RedisShardedPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by Choisaaaa on 2018/7/28.
 * 管理员身份拦截器
 * 实现的功能是如果是以admin身份进来，不能执行写操作
 */
public class AdminInterceptor implements HandlerInterceptor {
    final String Origin = PropertiesUtil.getProperty("admin.origin");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getHeader("Origin").equals(Origin)) {
            Admin currentAdmin = null;
            String adminLoginToken = CookieUtil.readAdminLoginToken(request);
            if (StringUtils.isNotEmpty(adminLoginToken)) {
                String adminJsonStr = RedisShardedPoolUtil.get(adminLoginToken);
                currentAdmin = JsonUtil.string2Obj(adminJsonStr, Admin.class);
            }
            if (currentAdmin == null) {
                PrintWriter out = response.getWriter();
                out.print(JsonUtil.obj2String(ServerResponse.createByNeedLogin()));
                out.flush();
                out.close();// 这里要关闭
                return false;
            } else if (currentAdmin.getAdminName().equals("admin")) {
                PrintWriter out = response.getWriter();
                Map<String, Object> resultMap = Maps.newHashMap();
                resultMap.put("status", 1);
                resultMap.put("msg", "Sorry !The operation failed because you did not have permission");
                out.print(JsonUtil.obj2String(resultMap));
                out.flush();
                out.close();// 这里要关闭
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
